package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    //1:营业额统计
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //创建集合用来存储日期
        List<LocalDate> dateList = getDateList(begin, end);

        //查询数据库返回每一天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList){
            //获取当天的开始时间和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //封装map集合中进行查询数据库
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);
            Double money = orderMapper.SumByMap(map);
            //当营收额为0时，money为null，拼接时要改为0.0
            money = money == null ? 0.0 : money;
            turnoverList.add(money);
        }
        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    //2：用户统计接口
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //创建集合用来存储日期
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        //查询数据库返回每一天的用户数据
        for (LocalDate date : dateList){
            //获取当天的开始和结束时间
            LocalDateTime beginTime = LocalDateTime.of(date,LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date,LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer Total = userMapper.countByTimeTotal(map);
            Integer New = userMapper.countByTimeNew(map);
            Total = Total == null ? 0 : Total;
            New = New == null ? 0 : New;
            newUserList.add(New);
            totalUserList.add(Total);
        }
        return UserReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    //3：订单统计接口
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        //创建集合用来存储日期
        List<LocalDate> dateList = getDateList(begin, end);
        //有效订单数列表
        List<Integer> orderCountList = new ArrayList<>();
        //订单数列表
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            //获取当天的开始与结束时间
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status",Orders.COMPLETED);//5--代表已完成订单
            Integer numberFinally = orderMapper.NumberByMap(map);//当天完成订单的数量 -- 有效订单数
            map.put("status",null);
            Integer numberTotal = orderMapper.NumberByMap(map);//当天订单的数量 -- 订单总数
            orderCountList.add(numberFinally);//有效订单数
            validOrderCountList.add(numberTotal);//订单总数
        }
        //计算: - 订单完成率 - 订单总数 - 有效订单数 用stream流写
        Integer totalOrderCount = validOrderCountList.stream().mapToInt(Integer::intValue).sum();//订单总数
        Integer validOrderCount = orderCountList.stream().mapToInt(Integer::intValue).sum();//有效订单数
        Double CompletionRate = 0.0;
        if (totalOrderCount != 0){
            CompletionRate =  (double)validOrderCount/(double)totalOrderCount;
        }
        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))//有效订单数
                .validOrderCountList(StringUtils.join(validOrderCountList,","))//订单总数
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(CompletionRate)
                .build();
    }

    //4：查询销量排名top10
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        //获取这段时间的开始与结束时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",Orders.COMPLETED);//5--代表已完成订单
        List<GoodsSalesDTO> list = orderMapper.getNameAndNumber(map);
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        if  (list != null && list.size() > 0){
            //把list元素按照number大小排序，数量大的拍的靠前
            list.sort(new Comparator<GoodsSalesDTO>() {
                @Override
                public int compare(GoodsSalesDTO o1, GoodsSalesDTO o2) {
                    return o2.getNumber() - o1.getNumber();
                }
            });

            //把list的元素分成两list集合分别是nameList，numberList

            for (int i = 0; i < Math.min(10,list.size()); i++){
                nameList.add(list.get(i).getName());
                numberList.add(list.get(i).getNumber().toString());
            }
        }else {
            nameList.add("0");
            numberList.add("0");

        }

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    //导出Excel表格 --- 运营数据报表
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1：查询数据库，获得营业数据 --- 近30天的
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);
        //2：通过POI将数据写到Excel表格中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);
            XSSFRow row = sheet.getRow(3);

            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                //每一天的日期
                LocalDate date = begin.plusDays(i);
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date,LocalTime.MAX));
                //获取行对象
                XSSFRow row1 = sheet.getRow(i + 7);
                row1.getCell(1).setCellValue(date.toString());
                row1.getCell(2).setCellValue(businessData.getTurnover());
                row1.getCell(3).setCellValue(businessData.getValidOrderCount());
                row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row1.getCell(5).setCellValue(businessData.getUnitPrice());
                row1.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3：通过输出流将Excel表格下载到客户端浏览器
            OutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //创建集合用来存储日期
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}
